import { IFeidaoAiWeappPage } from '../../../../interfaces';

const FD_EVENTS_WX_INNER_AUDIO_CANPLAY = 'fd-events-wx-inner-audio-canplay';
const FD_EVENTS_WX_INNER_AUDIO_PLAY = 'fd-events-wx-inner-audio-play';
const FD_EVENTS_WX_INNER_AUDIO_PAUSE = 'fd-events-wx-inner-audio-pause';
const FD_EVENTS_WX_INNER_AUDIO_STOP = 'fd-events-wx-inner-audio-stop';
const FD_EVENTS_WX_INNER_AUDIO_ENDED = 'fd-events-wx-inner-audio-ended';
const FD_EVENTS_WX_INNER_AUDIO_ONTIMEUPDATA = 'fd-events-wx-inner-audio-ontimeupdata';
const FD_EVENTS_WX_INNER_AUDIO_ERROR = 'fd-events-wx-inner-audio-error';
const FD_EVENTS_WX_INNER_AUDIO_WAITING = 'fd-events-wx-inner-audio-waiting';
const FD_EVENTS_WX_INNER_AUDIO_SEEKING = 'fd-events-wx-inner-audio-seeking';
const FD_EVENTS_WX_INNER_AUDIO_SEEKED = 'fd-events-wx-inner-audio-seeked';

/**
 * @protected
 * @see [description](https://mp.weixin.qq.com/debug/wxadoc/dev/api/createInnerAudioContext.html)
 */
export default function create_inner_audio_context(fd: IFeidaoAiWeappPage, src?: string, startTime?: number, autoplay?: boolean, loop?: boolean, obeyMuteSwitch?: boolean) {
	if (!fd.data.fd.inner_audio_context) {
		const _ctx = fd.data.fd.inner_audio_context = wx.createInnerAudioContext();
		_ctx.onCanplay((errCode) => {
			fd.emit(FD_EVENTS_WX_INNER_AUDIO_CANPLAY, errCode);
		});
		_ctx.onPlay((errCode) => {
			fd.emit(FD_EVENTS_WX_INNER_AUDIO_PLAY, errCode);
		});
		_ctx.onPause((errCode) => {
			fd.emit(FD_EVENTS_WX_INNER_AUDIO_PAUSE, errCode);
		});
		_ctx.onStop((errCode) => {
			fd.emit(FD_EVENTS_WX_INNER_AUDIO_STOP, errCode);
		});
		_ctx.onEnded((errCode) => {
			fd.emit(FD_EVENTS_WX_INNER_AUDIO_ENDED, errCode);
		});
		_ctx.onTimeUpdate((errCode) => {
			fd.emit(FD_EVENTS_WX_INNER_AUDIO_ONTIMEUPDATA, errCode);
		});
		_ctx.onError((errCode) => {
			fd.emit(FD_EVENTS_WX_INNER_AUDIO_ERROR, errCode);
		});
		_ctx.onWaiting((errCode) => {
			fd.emit(FD_EVENTS_WX_INNER_AUDIO_WAITING, errCode);
		});
		_ctx.onSeeking((errCode) => {
			fd.emit(FD_EVENTS_WX_INNER_AUDIO_SEEKING, errCode);
		});
		_ctx.onSeeked((errCode) => {
			fd.emit(FD_EVENTS_WX_INNER_AUDIO_SEEKED, errCode);
		});
		return fd.data.fd.inner_audio_context;
	}

	const ctx = fd.data.fd.inner_audio_context;
	if (src !== undefined && ctx.src !== src) {
		ctx.src = src;
	}
	if (startTime !== undefined && ctx.startTime) {
		ctx.startTime = startTime;
	}
	if (autoplay !== undefined && ctx.autoplay) {
		ctx.autoplay = autoplay;
	}
	if (loop !== undefined && ctx.loop) {
		ctx.loop = loop;
	}
	if (obeyMuteSwitch !== undefined && ctx.obeyMuteSwitch) {
		ctx.obeyMuteSwitch = obeyMuteSwitch;
	}
	return ctx;
}
